#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/ioctl.h>

#define PORT 8888
#define BUFFER_SIZE 1024
#define MAX_RETRY_ATTEMPTS 3
#define RETRY_DELAY_MS 1000

class SocketServer {
private:
    int server_fd;
    int new_socket;
    struct sockaddr_in address;
    int addrlen;
    int is_connect;

public:
    SocketServer() : server_fd(-1), new_socket(-1), addrlen(sizeof(address)),is_connect(0) {
        memset(&address, 0, sizeof(address));
    }

    // 初始化服务器
    bool init() {
        int opt = 1;
        std::cout << "开始初始化服务器..." << std::endl;

        // 创建套接字文件描述符
        if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
            std::cerr << "创建套接字失败: " << strerror(errno) << std::endl;
            return false;
        }
        std::cout << "套接字创建成功 (fd=" << server_fd << ")" << std::endl;

        // 设置套接字选项
        if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
            std::cerr << "设置套接字选项失败: " << strerror(errno) << std::endl;
            return false;
        }
        std::cout << "套接字选项设置成功" << std::endl;

        address.sin_family = AF_INET;
        address.sin_addr.s_addr = INADDR_ANY;
        address.sin_port = htons(PORT);

        // 绑定套接字到指定地址和端口
        if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
            std::cerr << "绑定地址和端口失败: " << strerror(errno) << std::endl;
            return false;
        }
        std::cout << "成功绑定到端口 " << PORT << std::endl;

        // 监听连接
        if (listen(server_fd, 3) < 0) {
            std::cerr << "监听失败: " << strerror(errno) << std::endl;
            return false;
        }
        std::cout << "服务器初始化完成，正在监听端口 " << PORT << " (最大等待队列: 3)" << std::endl;
        return true;
    }

    // 接受连接（阻塞等待）
    bool accept_connection() {
        if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
            std::cerr << "接受连接失败: " << strerror(errno) << std::endl;
            is_connect = 0;
            return false;
        }
        is_connect = 1;
        return true;
    }

    // 接收消息
    ssize_t receive(char *buffer, size_t buffer_size) {
        return recv(new_socket, buffer, buffer_size, 0);
    }

    // 重新连接
    bool reconnect() {
        // 关闭现有连接
        if (new_socket != -1) {
            ::close(new_socket);
            new_socket = -1;
            is_connect = 0;
        }

        // 重新接受连接
        std::cout << "尝试重新连接..." << std::endl;
        return accept_connection();
    }

    // 发送消息（带重试）
    ssize_t send(const char *message) {
        size_t len = strlen(message);
        int retry_count = 0;

        while (retry_count < MAX_RETRY_ATTEMPTS) {
            ssize_t sent = ::send(new_socket, message, len, 0);
            if (sent == static_cast<ssize_t>(len)) {
                return sent; // 发送成功
            }

            if (sent == -1) {
                std::cerr << "发送失败，错误: " << strerror(errno) << std::endl;
                if (errno == ECONNRESET || errno == EPIPE) {
                    std::cout << "连接断开，尝试重连 (尝试 " << retry_count + 1 << "/" << MAX_RETRY_ATTEMPTS << ")" << std::endl;
                    if (reconnect()) {
                        retry_count++;
                        usleep(RETRY_DELAY_MS * 1000); // 等待一段时间再重试
                        continue;
                    }
                }
            }
            retry_count++;
            usleep(RETRY_DELAY_MS * 1000);
        }

        std::cerr << "达到最大重试次数，发送失败" << std::endl;
        return -1;
    }

    // 发送 std::vector<uint32_t> 数据（带重试）
    bool send_vector(const std::vector<uint32_t>& data) {
        size_t size = data.size();
        int retry_count = 0;

        while (retry_count < MAX_RETRY_ATTEMPTS) {
            try {
                // 先发送数据大小
                ssize_t size_sent = ::send(new_socket, &size, sizeof(size), 0);
                if (size_sent != static_cast<ssize_t>(sizeof(size))) {
                    if (size_sent == -1 && (errno == ECONNRESET || errno == EPIPE)) {
                        std::cout << "发送大小信息时连接断开，尝试重连 (尝试 " << retry_count + 1 << "/" << MAX_RETRY_ATTEMPTS << ")" << std::endl;
                        if (reconnect()) {
                            retry_count++;
                            usleep(RETRY_DELAY_MS * 1000);
                            continue;
                        }
                    }
                    std::cerr << "发送向量大小失败: " << strerror(errno) << std::endl;
                    retry_count++;
                    usleep(RETRY_DELAY_MS * 1000);
                    continue;
                }

                // 再发送数据内容
                ssize_t data_sent = ::send(new_socket, data.data(), size * sizeof(uint32_t), 0);
                if (data_sent != static_cast<ssize_t>(size * sizeof(uint32_t))) {
                    if (data_sent == -1 && (errno == ECONNRESET || errno == EPIPE)) {
                        std::cout << "发送数据时连接断开，尝试重连 (尝试 " << retry_count + 1 << "/" << MAX_RETRY_ATTEMPTS << ")" << std::endl;
                        if (reconnect()) {
                            retry_count++;
                            usleep(RETRY_DELAY_MS * 1000);
                            continue;
                        }
                    }
                    std::cerr << "发送向量数据失败: " << strerror(errno) << std::endl;
                    retry_count++;
                    usleep(RETRY_DELAY_MS * 1000);
                    continue;
                }

                return true; // 发送成功
            }
            catch(const std::exception& e) {
                std::cerr << "发送异常: " << e.what() << std::endl;
                retry_count++;
                if (retry_count < MAX_RETRY_ATTEMPTS) {
                    std::cout << "将在" << RETRY_DELAY_MS << "ms后重试" << std::endl;
                    usleep(RETRY_DELAY_MS * 1000);
                }
            }
        }

        std::cerr << "达到最大重试次数，发送失败" << std::endl;
        return false;
    }

    // 关闭连接
    void close() {
        if (new_socket != -1) {
            // 等待所有数据发送完成
            int pending = 0;
            do {
                ioctl(new_socket, TIOCOUTQ, &pending);
                if (pending > 0) {
                    usleep(1000); // 等待1ms
                }
            } while (pending > 0);

            ::close(new_socket);
            new_socket = -1;
        }
        if (server_fd != -1) {
            ::close(server_fd);
            server_fd = -1;
        }
        std::cout << "Connection closed" << std::endl;
    }

    ~SocketServer() {
        // 自动关闭连接
        close();
    }
};



// int main() {
//     SocketServer server;
//     if (!server.init()) {
//         return 1;
//     }
//     if (!server.accept_connection()) {
//         return 1;
//     }
//     char buffer[BUFFER_SIZE] = {0};
//     // 接收消息
//     ssize_t bytes_received = server.receive(buffer, BUFFER_SIZE);
//     if (bytes_received > 0) {
//         std::cout << "Received from client: " << buffer << std::endl;
//     }
//     // 发送消息
//     const char *response = "Hello from C++ server!";
//     server.send(response);
//     return 0;
// }
    